#-*- coding: big5 -*-
import re
from modelRepository import modelRepository
from page import Page
from log import log

class PageBuilderDirector:
    def __init__(self):
        self.lstPage=[]
        self.intPageCursor=0
    def getNextPageString(self):
        self.intPageCursor+=1
        return self.lstPage[self.intPageCursor].strPageContent
    def getPreviousPageString(self):
        self.intPageCursor-=1
        return self.lstPage[self.intPageCursor].strPageContent
    def construct(self):
        book=modelRepository.getModelBook()
        visitorBuildPage=VisitorBuildPage()
        visitorBuildPage.startTraverse()
        self.lstPage=visitorBuildPage.getLstPage()
    def getPageString(self,intPageNum):
        return self.lstPage[intPageNum].strPageContent

class PageBuilder:
    def __init__(self):
        self.intMaxHeight=3
        self.page=Page()
        self.lstPage=[]
    def addLine(self,strLine):
        if not self.page.canAddLine():
            self.lstPage.append(self.page)
            self.page=Page()
        self.page.addLine(strLine)
    def getLstPage(self):
        return self.lstPage
    
class Visitor:
    def traverse(self,lstBookComponent):
       if not lstBookComponent: return
       for bookComponent in lstBookComponent:
           if bookComponent.isLeaf():
               bookComponent.accept(self)
           else:
               bookComponent.accept(self)
               self.traverse(bookComponent.lstBookComponent)
    def startTraverse(self):
        book=modelRepository.getModelBook()
        book.accept(self)
        self.traverse(book.lstBookComponent)
    def visitBook(self,bookComponent): pass
    def visitParagraph(self,bookComponent): pass
    def visitBulletItem(self,bookComponent): pass
    def visitUnorderedList(self,bookComponent): pass
    def visitSection(self,bookComponent): pass
    def visitChapter(self,bookComponent): pass
    
class VisitorBuildPage(Visitor):
    def __init__(self):
        self.pageBuilder=PageBuilder()
    def getLstPage(self):
        return self.pageBuilder.getLstPage()
    def visitBook(self,bookComponent):
        book=bookComponent
        self.pageBuilder.addLine('Book Title:%s'%book.strText)
        self.pageBuilder.addLine('Book Author:%s'%book.strAuthor)        
    def visitParagraph(self,bookComponent): self.visitDefault(bookComponent)
    def visitBulletItem(self,bookComponent): self.visitDefault(bookComponent)
    def visitUnorderedList(self,bookComponent): self.visitDefault(bookComponent)
    def visitSection(self,bookComponent): self.visitDefault(bookComponent)
    def visitChapter(self,bookComponent): self.visitDefault(bookComponent)
    def visitDefault(self,bookComponent):
        self.pageBuilder.addLine(bookComponent.strText)
    